<?php
class ImgStorage
{
    private $_dir;

    public function __construct($dir = '/usr/local/apache2/htdocs/jibaiwang/')
    {
        $this->_dir = $dir;        
    }

    public function store($buffer, $type)
    {
        $md5 = md5($buffer);
        $hash = crc32($md5) % 8;
        $filename = 'img/' . $hash . '/' . $md5 . '.' . $type;
        $full_filename = $this->_dir . $filename;

        $size = file_put_contents($full_filename, $buffer);

        if($size == strlen($buffer))
        {
            return $filename;
        }
        else
        {
            return False;
        }
    }
}

/* example
$a = new ImgStorage();
//$buf = file_get_contents('http://pic21.nipic.com/20120512/6751438_134453111107_2.jpg');
$buf = file_get_contents($argv[1]);
var_dump(md5($buf));
$res = $a->store($buf, 'jpg');
var_dump($res);
*/
